#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
using namespace std;

namespace ThreadModule
{
    template <typename T>
    using func_t = std::function<void(T)>;


    //T------ ThreadData*
    template <class T>
    class Thread
    {
        void Excute()
        {
            _func(_data);
        }

    public:
        Thread(func_t<T> func, T data, const string threadname = "new thread")
            : _tid(0), _func(func), _data(data), _threadname(threadname), _stop(true)
        {
        }
        static void *threadroutine(void *args)
        {
            Thread<T> *self = static_cast<Thread<T> *>(args);
            self->Excute();
            return nullptr;
        }
        bool Start()
        {
            int retval = pthread_create(&_tid, nullptr, threadroutine, this);
            if (retval == 0)
            {
                _stop = false;
                return true;
            }
            else
            {
                return false;
            }
        }

        void Join()
        {
            if (_stop != true)
            {
                pthread_join(_tid, nullptr);
            }
        }

        void Detach()
        {
            if (_stop != true)
            {
                pthread_detach(_tid);
            }
        }

        string threadname()
        {
            return _threadname;
        }

        void Stop()
        {
            _stop = true;
        }

    private:
        pthread_t _tid;
        func_t<T> _func;
        T _data;
        string _threadname;
        bool _stop;
    };
}